<template>
  <div class="statistics">
    <h2>数据统计</h2>

    <div class="stats-cards">
      <div class="stat-card">
        <div class="stat-title">总用户数</div>
        <div class="stat-value">{{ stats.totalUsers }}</div>
        <div class="stat-trend" :class="{ 'up': stats.userGrowth > 0, 'down': stats.userGrowth < 0 }">
          {{ stats.userGrowth > 0 ? '+' : '' }}{{ stats.userGrowth }}%
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总订单数</div>
        <div class="stat-value">{{ stats.totalOrders }}</div>
        <div class="stat-trend" :class="{ 'up': stats.orderGrowth > 0, 'down': stats.orderGrowth < 0 }">
          {{ stats.orderGrowth > 0 ? '+' : '' }}{{ stats.orderGrowth }}%
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">总销售额</div>
        <div class="stat-value">¥{{ stats.totalRevenue }}</div>
        <div class="stat-trend" :class="{ 'up': stats.revenueGrowth > 0, 'down': stats.revenueGrowth < 0 }">
          {{ stats.revenueGrowth > 0 ? '+' : '' }}{{ stats.revenueGrowth }}%
        </div>
      </div>
      <div class="stat-card">
        <div class="stat-title">平均订单金额</div>
        <div class="stat-value">¥{{ stats.averageOrderValue }}</div>
        <div class="stat-trend" :class="{ 'up': stats.aovGrowth > 0, 'down': stats.aovGrowth < 0 }">
          {{ stats.aovGrowth > 0 ? '+' : '' }}{{ stats.aovGrowth }}%
        </div>
      </div>
    </div>

    <div class="charts-container">
      <div class="chart-card">
        <h3>销售趋势</h3>
        <div class="chart" ref="salesChart"></div>
      </div>
      <div class="chart-card">
        <h3>商品分类占比</h3>
        <div class="chart" ref="categoryChart"></div>
      </div>
    </div>

    <div class="data-tables">
      <div class="table-card">
        <h3>热销商品</h3>
        <table>
          <thead>
            <tr>
              <th>商品名称</th>
              <th>销量</th>
              <th>销售额</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="product in stats.topProducts" :key="product.id">
              <td>{{ product.name }}</td>
              <td>{{ product.sales }}</td>
              <td>¥{{ product.revenue }}</td>
            </tr>
          </tbody>
        </table>
      </div>
      <div class="table-card">
        <h3>最近订单</h3>
        <table>
          <thead>
            <tr>
              <th>订单号</th>
              <th>用户</th>
              <th>金额</th>
              <th>状态</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="order in stats.recentOrders" :key="order.id">
              <td>{{ order.id }}</td>
              <td>{{ order.username }}</td>
              <td>¥{{ order.amount }}</td>
              <td>
                <span :class="['status-badge', order.status]">
                  {{ getStatusText(order.status) }}
                </span>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</template>

<script>
import { API_ENDPOINTS } from '../../config/api';
import axios from 'axios';
import * as echarts from 'echarts';

export default {
  name: 'StatisticsView',
  data() {
    return {
      stats: {
        totalUsers: 0,
        userGrowth: 0,
        totalOrders: 0,
        orderGrowth: 0,
        totalRevenue: 0,
        revenueGrowth: 0,
        averageOrderValue: 0,
        aovGrowth: 0,
        topProducts: [],
        recentOrders: []
      },
      salesChart: null,
      categoryChart: null
    };
  },
  methods: {
    async fetchStats() {
      try {
        const response = await axios.get(API_ENDPOINTS.STATS.GET_ALL);
        this.stats = response.data;
        this.initCharts();
      } catch (error) {
        console.error('获取统计数据失败:', error);
        alert('获取统计数据失败');
      }
    },
    initCharts() {
      // 初始化销售趋势图表
      this.salesChart = echarts.init(this.$refs.salesChart);
      this.salesChart.setOption({
        title: {
          text: '近30天销售趋势'
        },
        tooltip: {
          trigger: 'axis'
        },
        xAxis: {
          type: 'category',
          data: this.stats.salesTrend.map(item => item.date)
        },
        yAxis: {
          type: 'value'
        },
        series: [{
          data: this.stats.salesTrend.map(item => item.amount),
          type: 'line',
          smooth: true,
          areaStyle: {}
        }]
      });

      // 初始化商品分类占比图表
      this.categoryChart = echarts.init(this.$refs.categoryChart);
      this.categoryChart.setOption({
        title: {
          text: '商品分类销售占比'
        },
        tooltip: {
          trigger: 'item'
        },
        legend: {
          orient: 'vertical',
          left: 'left'
        },
        series: [{
          type: 'pie',
          radius: '50%',
          data: this.stats.categoryDistribution.map(item => ({
            name: item.category,
            value: item.amount
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 0, 0, 0.5)'
            }
          }
        }]
      });
    },
    getStatusText(status) {
      const statusMap = {
        pending: '待处理',
        processing: '处理中',
        completed: '已完成',
        cancelled: '已取消'
      };
      return statusMap[status] || status;
    },
    handleResize() {
      this.salesChart?.resize();
      this.categoryChart?.resize();
    }
  },
  mounted() {
    this.fetchStats();
    window.addEventListener('resize', this.handleResize);
  },
  beforeUnmount() {
    window.removeEventListener('resize', this.handleResize);
    this.salesChart?.dispose();
    this.categoryChart?.dispose();
  }
};
</script>

<style scoped>
.statistics {
  padding: 20px;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.stat-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.stat-title {
  color: #666;
  font-size: 0.9em;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 1.8em;
  font-weight: bold;
  margin-bottom: 8px;
}

.stat-trend {
  font-size: 0.9em;
}

.stat-trend.up {
  color: #2ecc71;
}

.stat-trend.down {
  color: #e74c3c;
}

.charts-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.chart-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.chart-card h3 {
  margin-bottom: 20px;
}

.chart {
  height: 300px;
}

.data-tables {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
  gap: 20px;
}

.table-card {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.table-card h3 {
  margin-bottom: 20px;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th, td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #eee;
}

th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 0.9em;
}

.status-badge.pending {
  background-color: #f1c40f;
  color: white;
}

.status-badge.processing {
  background-color: #3498db;
  color: white;
}

.status-badge.completed {
  background-color: #2ecc71;
  color: white;
}

.status-badge.cancelled {
  background-color: #e74c3c;
  color: white;
}
</style> 